import swal from "sweetalert2";
import router from "../../../router";
import store from "../../../store/index";
import axios from "axios";
import qs from "qs";
var md5 = require("md5");
import { Loading, MessageBox } from "element-ui";
var getJsonOne = function(data, id) {
  for (var i in data) {
    if (data[i].id == id) {
      console.log(data[i], 22222);
      return data[i];
    } else {
      // eslint-disable-next-line no-undef
      getJsonOne(data[i].z, id);
    }
  }
};
const toChinesNum = (num) => {
  let changeNum = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]; //changeNum[0] = "零"
  let unit = ["", "十", "百", "千", "万"];
  num = parseInt(num);
  let getWan = (temp) => {
    let strArr = temp
      .toString()
      .split("")
      .reverse();
    let newNum = "";
    for (var i = 0; i < strArr.length; i++) {
      newNum =
        (i == 0 && strArr[i] == 0
          ? ""
          : i > 0 && strArr[i] == 0 && strArr[i - 1] == 0
          ? ""
          : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i])) +
        newNum;
    }
    return newNum;
  };
  let overWan = Math.floor(num / 10000);
  let noWan = num % 10000;
  if (noWan.toString().length < 4) noWan = "0" + noWan;
  return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
};
// var text="ssss"
const alertSuccess = ({ text: text, url: url }) => {
  text = text || "操作成功";
  swal({
    title: text,
    type: "success",
    confirmButtonColor: "#4aa6fc",
    confirmButtonText: "确定",
  }).then(function(isConfirm) {
    if (isConfirm.value == true && url) {
      router.push(url);
    }
  });
};
const alertError = (text1, text2, type) => {
  type = type || "error";
  swal({
    title: text1,
    text: text2,
    type: type,
    confirmButtonColor: "#4aa6fc",
    confirmButtonText: "确定",
  });
};
var parentNode = null;
var node = null;
const getNode = function(json, nodeId, time) {
  if (time != new Date()) {
    node = null;
  }
  //1.第一层 root 深度遍历整个JSON
  for (var i = 0; i < json.length; i++) {
    if (node) {
      break;
    }
    var obj = json[i];
    //没有就下一个
    if (!obj || !obj.id) {
      continue;
    }

    //2.有节点就开始找，一直递归下去
    // console.log(obj.url.indexOf(nodeId))
    if (obj.url == nodeId) {
      //找到了与nodeId匹配的节点，结束递归
      node = obj;
      break;
    } else {
      //3.如果有子节点就开始找
      if (obj.z) {
        //4.递归前，记录当前节点，作为parent 父亲
        obj.index = i;
        parentNode = obj;
        //递归往下找
        getNode(obj.z, nodeId);
      } else {
        //跳出当前递归，返回上层递归
        continue;
      }
    }
  }

  //5.如果木有找到父节点，置为null，因为没有父亲
  if (!node) {
    parentNode = null;
  }

  //6.返回结果obj
  return {
    parentNode: parentNode,
    node: node,
  };
};

const regexp = function(ex, str) {
  if (ex.test(str)) {
    return true;
  } else {
    return false;
  }
};
const getImgUrl = function(url) {
  if (url == "" || url == undefined) {
    return require("../../img/productDefault.jpg");
  }
  if (url.indexOf("blob") >= 0) {
    return url;
  }

  if (url.indexOf("assets") >= 0) {
    return url;
  } else if (url.indexOf("data") >= 0) {
    return url;
  } else if (url.indexOf("http") >= 0) {
    // return url + "?" + new Date().getTime();
    return url;
  } else if (url.indexOf("api") >= 0) {
    // return url + "?" + new Date().getTime();
    return url;
  } else {
    return "/api/" + url;
  }
};
const getImgVideo = function(url) {
  if (url == "" || url == undefined) {
    return false;
  }
  if (url.indexOf("assets") >= 0) {
    return url;
  } else if (url.indexOf("data") >= 0) {
    return url;
  } else if (url.indexOf("api") >= 0 || url.indexOf("http") >= 0) {
    return url;
  } else {
    return "/api/" + url;
  }
};
const getComposeByArrays = function(arrays) {
  for (var i = 0; i < arrays.length; i++) {
    if (arrays[i] == undefined) {
      arrays[i] = [""];
    }

    if (i > 100) {
      break;
    }
  }

  let arr = [""]; // 开始时待组合数组为空
  for (
    let i = 0;
    i < arrays.length;
    i++ //遍历二维数组 让当前数组与下一个数组继续组合
  ) {
    arr = two_compose(arr, arrays[i]); //两个数组组合 并返回组合后的数组
  }
  let arr1 = [];
  for (var i = 0; i < arr.length; i++) {
    arr1.push(arr[i].slice(1).split(","));
  }
  return arr1;
};

const two_compose = function(arr1, arr2) {
  //arr1为上次组合形成的数组 arr2 为二维数组里的下一个数组
  let arr = [];
  for (let i = 0; i < arr1.length; i++) {
    let v1 = arr1[i];
    for (let j = 0; j < arr2.length; j++) {
      let v2 = arr2[j];
      let value = v1 + "," + v2; //每一项进行组合
      arr.push(value);
    }
  }
  return arr;
};
const uniq = function(array) {
  var temp = []; //一个新的临时数组
  for (var i = 0; i < array.length; i++) {
    if (temp.indexOf(array[i]) == -1) {
      temp.push(array[i]);
    }
  }
  return temp;
};
const arrOrObj = function(array) {
  // 数组转对象
  var arr = {};
  for (var i in array) {
    var str = array[i].split(":");
    arr[str[0]] = str[1];
  }
  return arr;
};
const objOrArr = function(obj) {
  var arr = [];
  for (var i in obj) {
    var str = i + ":" + obj[i];
    arr.push(str);
  }
  return arr;
};
const vuetime = function(time) {
  if (time == null || time == "" || time == undefined) {
    return "";
  }
  if (time != 0) {
    if (time.length < 13) {
      time = time + "000";
    }
  } else {
    time = "";
  }
  return time;
};
const phptime = function(time) {
  if (time == null || time == "" || time == undefined) {
    return "";
  }
  var mytime = time.toString();
  var pt = mytime.substring(0, mytime.length - 3);
  return pt;
};

const tomenu = function(url, obj) {
  if (url == null) {
    alertError("出错啦！", "地址为空");
    return false;
  }
  if (obj && url && url != "/login" && url != "/") {
    var a = {};
    for (var i in obj) {
      if (obj[i].url == url) {
        a = obj[i];
      } else {
        if (obj[i].z) {
          for (var j in obj[i].z) {
            if (obj[i].z[j].url == url) {
              a = obj[i].z[j];
            } else {
              if (obj[i].z[j].z) {
                for (var k in obj[i].z[j].z) {
                  if (obj[i].z[j].z[k].url == url) {
                    a = obj[i].z[j].z[k];
                  }
                }
              }
            }
          }
        }
      }
    }
    var data = a;
    if (data.title != undefined) {
      store.commit("setTitle", data.title);
      store.commit("setParentTtile", data.parent_title);
      store.commit("setTitle2", data.title);
      router.push(url);
    } else {
      alertError("出错啦！", "地址与栏目地址不匹配");
    }
  }
};
const toFixedZ = function(num, decimal) {
  num = num + "";
  num = num.toString();
  // decimal= decimal || 2;
  decimal = decimal >= 2 && decimal < 6 ? 2 : decimal;
  decimal = decimal == "0" ? 0 : decimal || 2;
  let index = num.indexOf(".");
  if (index !== -1) {
    num = num.substring(0, decimal + index + 1);
  } else {
    num = num.substring(0);
  }
  return parseFloat(num).toFixed(decimal);
};
const postExcelFile = function(obj, serveurl) {
  var params = JSON.parse(JSON.stringify(obj));
  MessageBox.confirm("是否确认导出？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    var loading = Loading.service({
      lock: true,
      text: "加载中，请稍后",
      background: "rgba(0, 0, 0, 0.7)",
    });

    //params是post请求需要的参数，url是请求url地址
    var uid = localStorage.getItem("adminuid") || "";
    var time = parseInt(new Date().getTime() / 1000) + "";
    var admin_key = localStorage.getItem("admin_key") || "";
    var str = qs.stringify(params);
    var url = "";
    if (str == "") {
      url =
        "admin_key=" +
        admin_key +
        "&headuid=" +
        uid +
        "&timestamp=" +
        time +
        "&meid=" +
        "" +
        "&extra=" +
        "";
    } else {
      url =
        str +
        "&admin_key=" +
        admin_key +
        "&headuid=" +
        uid +
        "&timestamp=" +
        time +
        "&meid=" +
        "" +
        "&extra=" +
        "";
    }
    var arr = url.split("&");
    for (var i in arr) {
      if (arr[i].indexOf("%") >= 0) {
        arr[i] = decodeURIComponent(arr[i]);
      }
    }
    var urlStr = arr.sort().join("&");
    params.sign = md5("@" + urlStr + "@");

    axios({
      method: "post",
      url: serveurl,
      data: qs.stringify(params),
      headers: {
        headuid: uid,
        timestamp: time,
        meid: "",
        extra: "",
      },
      responseType: "blob",
    })
      .then((data) => {
        loading.close();
        if (data.status == 200) {
          // 截取文件名，这里是后端返回了文件名+后缀，如果没有可以自己拼接
          let fileName = decodeURI(
            data.headers["content-disposition"].split(";")[1].split("=")[1]
          );
          var reg = /^[\'\"]+|[\'\"]+$/g;
          fileName = fileName.replace(reg, "");
          // 将`blob`对象转化成一个可访问的`url`
          let url = window.URL.createObjectURL(new Blob([data.data]));
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } else {
          alertError(data.data.result, data.data.code_desc);
        }
      })
      .catch(() => {
        alertError("数据不存在，导出失败");
        loading.close();
      });
  });
};
const getMenuInfo = function(arr, data, city = []) {
  if (typeof data === "object") {
    for (let i = 0; arr[i] !== undefined; i++) {
      for (let j = 0; data[j] !== undefined; j++) {
        if (arr[i] === data[j].url) {
          city.push(data[j]);
          return city;
        }
      }
    }
    for (let i = 0; data[i] !== undefined; i++) {
      getMenuInfo(arr, data[i].z, city);
    }
  }
  return city;
};
const getParent = function(arr, data, city = []) {
  if (typeof data === "object") {
    for (let i = 0; arr[i] !== undefined; i++) {
      for (let j = 0; data[j] !== undefined; j++) {
        if (arr[i] === data[j].id) {
          city.push(data[j]);
        }
      }
    }
    for (let i = 0; data[i] !== undefined; i++) {
      getParent(arr, data[i].z, city);
    }
  }
  return city;
};

const deleteNumber = function(str) {
  str = str + "";
  return str.replace(/[0-9]/gi, "");
};
var parentNodeUrl = null;
var nodeUrl = null;
const getNodeUrl = function(json, nodeId, time) {
  if (time != new Date().getTime()) {
    nodeUrl = null;
  }
  //1.第一层 root 深度遍历整个JSON
  for (var i = 0; i < json.length; i++) {
    if (nodeUrl) {
      break;
    }
    var obj = json[i];
    //没有就下一个
    if (!obj || !obj.id) {
      continue;
    }

    //2.有节点就开始找，一直递归下去
    var url = null;

    if (obj.url_details.indexOf("|") >= 0) {
      url = obj.url_details.split("|");
    } else {
      url = obj.url_details;
    }
    if (obj.url === nodeId && obj.three != "三") {
      url = obj.url;
    }
    if (typeof url == "object") {
      for (var k in url) {
        if (url[k] == nodeId) {
          nodeUrl = obj;
          break;
        }
      }
    } else if (url == nodeId) {
      console.log(obj);
      nodeUrl = obj;
      break;
      //找到了与nodeId匹配的节点，结束递归
    } else {
      //3.如果有子节点就开始找
      if (obj.z) {
        //4.递归前，记录当前节点，作为parent 父亲
        obj.index = i;
        parentNodeUrl = obj;
        //递归往下找
        getNodeUrl(obj.z, nodeId);
      } else {
        //跳出当前递归，返回上层递归
        continue;
      }
    }
  }

  //5.如果木有找到父节点，置为null，因为没有父亲
  if (!node) {
    parentNodeUrl = null;
  }

  //6.返回结果obj
  return {
    parentNodeUrl: parentNodeUrl,
    nodeUrl: nodeUrl,
  };
};
const imgUploadBase64 = function(path, callback) {
  var img = new Image();
  img.src = path;
  // base64地址图片加载完毕后执行
  img.onload = () => {
    // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    // 图片原始尺寸
    var originWidth = img.width;
    var originHeight = img.height;
    // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
    var maxWidth = 750,
      maxHeight = img.height;
    // 目标尺寸
    var targetWidth = originWidth,
      targetHeight = originHeight;
    // 图片尺寸超过最大尺寸的限制
    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > maxWidth / maxHeight) {
        // 更改宽度，按照宽度限定尺寸
        targetWidth = maxWidth;
        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
      } else {
        targetHeight = maxHeight;
        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
      }
    }
    //对图片进行缩放
    canvas.width = targetWidth;
    canvas.height = targetHeight;

    // 清除画布
    context.clearRect(0, 0, targetWidth, targetHeight);
    context.fillStyle = "#fff";
    context.fillRect(0, 0, canvas.width, canvas.height);
    // 图片压缩
    context.drawImage(img, 0, 0, targetWidth, targetHeight);
    /*第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
    //压缩后的base64文件
    var newUrl = canvas.toDataURL("image/jpeg", 0.92);

    let file = convertBase64UrlToBlob(newUrl);

    var fd = new FormData();
    fd.append("file", file, "file_" + Date.parse(new Date()) + ".jpg");
    // fd.append("folder", 'product');

    let config = {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    };

    axios.post("/api/common/upload/index/", fd, config).then((res) => {
      if (res.data.code == 200) {
        if (typeof callback === "function") {
          //调用它，既然我们已经确定了它是可调用的
          callback(res.data.result);
        }
        return true;
      } else {
        alertError("上传失败");
        return false;
      }
    });
  };
};
const convertBase64UrlToBlob = function(urlData) {
  let bytes = window.atob(urlData.split(",")[1]); //去掉url的头，并转换为byte
  //处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length);
  let ia = new Uint8Array(ab);
  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], {
    type: "image/png",
  });
};

const getSendRow = function(row) {
  if (row == null) return false;
  var desc, links;
  if (!row.disable && row.title == "自定义链接") {
    row.links = " ";
    return row;
  }
  if (row.url) {
    links = row.url;
  }
  desc = row.url_title;

  if (row.url_title == "产品分类" && row.click_title == "供应商分类") {
    links = "/pages/shop/supplier/supplier?cate=" + row.id;
    desc = row.title + "分类供应商店铺";
    return;
  }
  if (row.url_title == "产品分类" && row.click_title != "供应商分类") {
    links = "/shop/shopsearch?cate_id=" + row.id;
    desc = row.title || "";
  }
  if (row.url_title == "旅游产品分类") {
    links = "/tourshop/cate?cate_id=" + row.id;
    desc = row.title || "";
  }
  if (row.url_title == "插件管理") {
    links = row.url || "";
    desc = row.title || "";
  }

  if (row.url_title == "商品选择") {
    links = "/pages/shop/shopdetail/shopdetail?id=" + row.id;
    desc = row.title || "";
  }
  if (row.url_title == "文章添加") {
    links = "/pages/news/newsdetail/newsdetail?id=" + row.id;
    desc = "文章：" + row.title || "";
  }
  if (row.url_title == "资讯分类") {
    links = "/news?cate_id=" + row.id;
    desc = row.title;
  }
  if (row.url_title == "商品分类2") {
    links = "/shop/shopslide?cate_id=" + row.id;
    desc = row.title || "";
  }
  if (row.url_title == "房产分类") {
    links = "/estate/list?cate_id=" + row.id;
    desc = row.title;
  }
  if (row.url_title == "表单") {
    links = "/pages/sub/form/form?id=" + row.id;
    desc = row.title;
  }
  if (row.url_title == "课程分类") {
    links = "/pages/lesson/lessoncate/lessoncate?id=" + row.id;
    desc = row.title;
  }
  return { links, desc, index: row.index };
};
const copyVal = function(val) {
  var oInput = document.createElement("input");
  oInput.value = val;
  document.body.appendChild(oInput);
  oInput.select();
  document.execCommand("Copy");
  oInput.className = "oInput";
  oInput.style.display = "none";
  alertSuccess("复制成功");
};
export default {
  getJsonOne,
  toChinesNum,
  alertSuccess,
  alertError,
  getNode,
  regexp,
  getImgUrl,
  getComposeByArrays,
  uniq,
  arrOrObj,
  objOrArr,
  vuetime,
  phptime,
  getImgVideo,
  tomenu,
  toFixedZ,
  postExcelFile,
  getMenuInfo,
  getParent,
  deleteNumber,
  getNodeUrl,
  imgUploadBase64,
  getSendRow,
  copyVal,
};
